<template>
  <div class="setup-rule">
    <div class="tag-list">
      <template v-if="dynamicTags && dynamicTags.length > 0">
        <el-tag
            :key="index"
            v-for="(item, index) in dynamicTags"
            :closable = "rQuery.state === 'add' || layerNum <= index"
            :disable-transitions="false"
            :effect="item.name === currentTag.name ? 'dark' : 'plain'"
            @click="onChangeRule(item, index)"
            @close="handleTagClose(index)">
          {{item.name}}
        </el-tag>
      </template>
      <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
      >
      </el-input>
      <el-button v-else class="button-new-tag" size="small" type="primary" plain @click="showInput">+ 添加分层</el-button>
    </div>
    <el-form class="currentTagForm" ref="currentTagForm" :rules="currentTagForm" size="small"  v-if="dynamicTags.length !== 0">
<!--      <el-form-item prop="name">-->
      <el-form-item>
        <el-input
            type="text"
            placeholder="请输入"
            v-model="currentTag.name"
            maxlength="30"
            show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item >
        <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入分层描述"
            maxlength="200"
            show-word-limit
            v-model="currentTag.desc">
        </el-input>
      </el-form-item>
      <el-form-item :label="ruleTitleLayered" filterable clearable prop="remarks" class="rule-linkage" v-if="typeStr === 1">
        <el-select
            v-model="currentTag.tagRuleCodes[0]"
            placeholder="请选择"
            filterable
            value-key="id"
            @change="firstColumnChangeAction($event, true)"
        >
          <el-option
              v-for="item in currentTag.columnList[0]"
              :key="item.code"
              :label="item.name"
              :value="item.code"
          >
          </el-option>
        </el-select>
        <el-select
            v-model="currentTag.tagRuleCodes[1]"
            :disabled = "currentTag.columnList[1].length === 0"
            filterable
            value-key="id"
            placeholder="请选择"
            @change="secondColumnChangeAction($event, true)"
        >
          <el-option
              v-for="item in currentTag.columnList[1]"
              :key="item.code"
              :label="item.name"
              :value="item.code"
          ></el-option>
        </el-select>
        <el-select
            v-if="rQuery.type !== 'group'"
            v-model="currentTag.tagRuleCodes[2]"
            :disabled = "currentTag.columnList[2].length === 0"
            filterable
            value-key="id"
            placeholder="请选择"
            @change="thirdColumnChangeAction($event, true)"
        >
          <el-option
              v-for="item in currentTag.columnList[2]"
              :key="item.code"
              :label="item.name"
              :value="item.code"
          ></el-option>
        </el-select>
<!--        {{currentTag.paramTypeList}}<br>-->
        <template v-if="currentTag.paramTypeList[0].dataType === 'address'">
          <br>
          <div class="fourth-column-list" >
<!--            address：{{currentTag.paramTypeList}}<br>-->
            <template v-for="(it, index) in currentTag.addressList">
<!--              {{currentTag.addressList[0]}}-->
              <span v-if="index === 0">选择</span>
              <el-select
                  v-model="currentTag.ruleValues[index][0]"
                  filterable :placeholder="'请选择'"
                  @change="getTagRuleParam('address', index, true)"
                  v-if="it.list.length !== 0">
                <el-option
                    v-for="item in it.list"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
              <!--
              <span v-if="index === 0">省-</span>
              <span v-if="index === 1">市-</span>
              <span v-if="index === 2">区</span>
              -->
            </template>
          </div>
        </template>
        <!--
        <template v-else-if="currentTag.selectList.list.length > 0">
          <div class="fourth-column-list" v-if="currentTag.selectList.list.length > 0">
            <el-select v-model="currentTag.ruleValues[0][0]" placeholder="请选择" size="small">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in currentTag.selectList.list" :key="index"></el-option>
            </el-select>
          </div>
        </template>
        -->
        <template v-else>
          <template v-for="(item, index) in currentTag.expressionArr">
            <div class="fourth-column-list">
              <template v-if="typeof item === 'number'">
                <template v-if="currentTag.paramTypeList[item] && currentTag.paramTypeList[item].typeFlag == 2">
                  <el-input v-model="currentTag.ruleValues[item][0]" oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </template>
                <template v-else-if="currentTag.paramTypeList[item] && currentTag.paramTypeList[item].typeFlag == 3">
                  <el-select v-model="currentTag.ruleValues[item][0]" placeholder="请选择" size="small" filterable>
                    <el-option :label="it.label" :value="it.value" v-for="(it, i) in labelSelectList[currentTag.paramTypeList[item].dataType]"></el-option>
                  </el-select>
                </template>
                <template v-else>
                  <el-input v-model="currentTag.ruleValues[item][0]" placeholder="请选择"></el-input>
                </template>
              </template>
              <template v-else>{{item}}</template>
            </div>
          </template>
        </template>
      </el-form-item>
      <!-- 程序化标签 才显示 -->
      <el-form-item label="更新方式" prop="remarks" class="update-method" v-if="rQuery.createWay == 1 || rQuery.type === 'group'">
        <el-radio-group v-model="updateWay">
          <template v-for="item in updateWayArr">
            <el-radio-button :label="item.dictId">{{ item.dictName }}</el-radio-button>
          </template>
        </el-radio-group>
      </el-form-item>
      <template v-if="rQuery.createWay == 1 || rQuery.type === 'group'">
      <span class="size12" v-if="updateWay==1">{{ updateWayText.text1 }}</span>
      <span class="size12" v-if="updateWay==2">{{ updateWayText.text2 }}</span>
      </template>
    </el-form>
  </div>
</template>

<script>

import common from '../mixins/common'
import apiFetch from "../../../api/apiFetch";

function CreateRule (name, index) {
  const obj = {}
  obj.name = name || '' // 标签分层名称
  obj.desc = '' // 标签分层说明
  obj.index = index || 0
  obj.sort = index || 0 // 排序
  obj.tagRuleCodes = ['', '', ''] // 标签类型代码
  obj.ruleCodes = ['', '', ''] // 人群类型代码
  obj.columnList = [[], [], []] // 标签类型代码 - 列表
  obj.ruleValues = [[''], [''], [''], [''], ['']] // 规则参数, 二维数组
  obj.expression = {} // 规则表达式
  obj.paramTypeList = [{ dataType: '' }] // 类型（1：文本；2数字；3：下拉框；4多级下拉选项）
  obj.selectList = { value: '', list: [] }
  obj.addressList = [
    { value: '', list: [] },
    { value: '', list: [] },
    { value: '', list: [] }
  ]
  return obj
}

export default {
  mixins: [common],
  name: 'SetupRule',
  props: {
    pDetails: {
      type: Object,
      default: () => {}
    },
    dataList: { // 数据列表
      type: Array,
      default: () => []
    },
    typeStr: { // 使用页面类型
      type: Number,
      default: () => 0
    },
    rQueryObj: { // 路由参数
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      currentTagForm: { name: [{ required: true, message: '请输入', trigger: 'blur' }] },
      dynamicTags: [],
      currentTag: {},
      inputVisible: false,
      inputValue: '',
      updateWayArr: [{ dictId: 1, dictName: '例行' }, { dictId: 2, dictName: '手动' }],
      updateWay: 1, // 更新方式
      tagRuleTypeList: [],
      dataType: 1,
      ruleParam: [], // 标签类型下拉参数类型数据查询接口
      rQuery: {},
      addressList: [],
      labelSelectList: {
        address: [],
        platform: [],
        brand: [],
        goods: []
      },
      ruleTitleLayered: '标签类型',
      updateWayText: {
        text1: '按天计算，标签每日凌晨更新。',
        text2: '标签生成后，点击"更新"进行数据的更新。'
      },
      layerNum: 100,
      isPass: false
    }
  },
  watch: {
    $route () {
      // this.testFun();
    },
    pDetails: {
      handler: function (value) {
        const rQuery = this.rQuery
        // this.getTagRuleTypeList() // 标签类型列表（三级树状）
        if (value.status === 999) {
          // return console.log('添加状态！')
          return
        }
        this.updateWay = value.updateWay
        const tempTagTierList = value.tagTierList
        if (tempTagTierList) {
          tempTagTierList.forEach(item => {
            if (rQuery && rQuery.type && rQuery.type === 'group') { item['tagRuleCodes'] = item.ruleCodes }
            const tempObj = new CreateRule()
            // if (!item.ruleValues || item.ruleValues.length === 0) { item.ruleValues = [[''], [''], [''], [''], ['']] }
            const obj = Object.assign({}, tempObj, item)
            // obj.columnList = [[], [], []] // 标签类型代码 - 列表
            this.dynamicTags.push(obj)
          })
          this.layerNum = this.dynamicTags.length
          // console.log(typeof this.layerNum, this.layerNum)
          this.dynamicTags.forEach((item, index) => {
            item.index = index
            item.sort = index
            item.columnList[0] = this.tagRuleTypeList
            if (rQuery && rQuery.type && rQuery.type === 'group') { item.desc = item.groupDesc }
          })
        }
        if (this.dynamicTags[0]) {
          // const temp = this.dynamicTags[0]
          // delete temp.columnList
          // this.currentTag = Object.assign(this.currentTag, this.dynamicTags[0])
          setTimeout(() => {
            Object.assign(this.currentTag, this.dynamicTags[0])
            this.firstColumnChangeAction(this.dynamicTags[0].tagRuleCodes[0])
          }, 1000)
        }
      },
      immediate: true
      // deep: true
    },
    currentTag: {
      deep: true,
      handler (newVal, oldVal) {
        if (newVal.name === '') {
          // this.$message.warning('规则名称不能为空！')
          // this.currentTag.name = oldVal.name
        }
      }
    }
  },
  mounted () { this.$nextTick(_ => {}) },
  created () { this.initialData() },
  methods: {
    initialData () {
      this.currentTag = new CreateRule()
      const rQuery = this.$route.query
      this.rQuery = rQuery
      this.getTagRuleTypeList()
      this.getAddressList() // 获取、省、市、区
      if (rQuery.type === 'group') {
        this.updateWayArr.splice(1, 1)
      }
      this.getLabelSelectList(this.labelSelectList).then(res => {
        // console.log(res)
      })
      this.onModifyText() // 修改文案
    },
    // 修改文案
    onModifyText () {
      const rQuery = this.$route.query
      if (rQuery.type === 'group') {
        this.ruleTitleLayered = '人群类型'
        this.updateWayText.text1 = '按天计算，人群每日凌晨更新。'
        this.updateWayText.text2 = '标签生成后，点击"更新"进行数据的更新。'
      }
    },
    async getLabelSelectList (selectList) {
      const sessionObj = JSON.parse(sessionStorage.getItem('labelSelectList'))
      const tempSelectList = Object.assign(selectList, sessionObj)
      // console.log(tempDictionaries)
      for (const type in tempSelectList) {
        if (tempSelectList[type].length > 0) {
          // continue
        } else {
          const params = { dataType: type, parentId: 0 }
          await this.$api.tagRuleParam(params).then((res) => {
            tempSelectList[type] = res.data
            // console.log(tempDictionaries[type])
          }).catch((err) => {
            console.log(err)
          })
        }
      }
      // console.log(tempDictionaries)
      sessionStorage.removeItem('labelSelectList')
      sessionStorage.setItem('labelSelectList', JSON.stringify(tempSelectList))
      this.labelSelectList = tempSelectList
      // console.log(this.labelSelectList)
      // return tempSelectList
    },
    // 删除 - tag
    handleTagClose (index) {
      // console.log('删除', this.dynamicTags.length)
      this.dynamicTags.splice(index, 1)

      console.log('删除', this.dynamicTags.length)
      if (this.dynamicTags.length > 0) {
        this.dynamicTags.forEach((item, index) => {
          item.index = index
          item.sort = index
        })
      /*
        this.currentTag = Object.assign({}, this.dynamicTags[0])
        this.firstColumnChangeAction(this.currentTag.tagRuleCodes[0])
        */
        this.currentTag = Object.assign({}, this.dynamicTags[0])
        this.firstColumnChangeAction(this.currentTag.tagRuleCodes[0])
        console.log(this.currentTag)
      } else {
        this.currentTag = new CreateRule()
      }
    },
    // 检查分层是否存在重名 -- 修改 - 提交时使用
    checkRepeat() {
      let isRepeat = false
      const dynamicTags = this.dynamicTags
      const len = dynamicTags.length
      for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
          if (i !== j && dynamicTags[i].name === dynamicTags[j].name) {
            console.log(dynamicTags[i].name)
            this.$message.warning('重名！')
            return isRepeat = true
          }
        }
      }
    },
    // 切换 - 标签
    onChangeRule (tag, index) {
      const currentTag = Object.assign({}, this.currentTag) // 旧
      const isPass = this.checkValues (currentTag)
      console.log(isPass, JSON.stringify(currentTag.expression) === '{}', currentTag)
      if (!isPass) { return this.$message.warning('切换前，请完善当前规则分层！') }
      this.dynamicTags[this.currentTag.index] = Object.assign({}, this.currentTag)
      this.currentTag = this.dynamicTags[index]
      this.firstColumnChangeAction(this.dynamicTags[index].tagRuleCodes[0])
    },
    // 获取值
    getRuleValues () {
      const currentTag = Object.assign({}, this.currentTag) // 旧
      const isPass = this.checkValues (currentTag)
      if (!isPass) {
        this.$message.warning('获取值，请完善当前规则分层！')
        return
      }
      this.dynamicTags[currentTag[currentTag.index]] = currentTag
    },
    checkValues (tag) {
      const rQuery = this.rQuery
      let isPass = false
      let isPassNum = 0
      const currentTag = JSON.parse(JSON.stringify(tag))
      /*
      const dynamicTags = this.dynamicTags
      dynamicTags.forEach(it => {
        if (it.name === currentTag.name) {
          console.log(it.name)
          this.$message.warning('重名！')
          isPass = false
          return
        }
      })
      */
      // console.log(currentTag)
      for (let key in currentTag) {
        switch (key) {
          case 'name': // 分层名称
            if (currentTag[key] !== '') {isPassNum++}
            // console.log(key, "：", currentTag[key])
            break
          case 'desc' || 'groupDesc': // 分层说明
            if (currentTag[key] !== '') {isPassNum++}
            // console.log(key, "：", currentTag[key])
            break
          case 'tagRuleCodes': // 标签类型代码
            if (this.typeStr === 1) {
              if (rQuery.type === 'group') {
                if (currentTag[key][1] && currentTag[key][1] !== '') {isPassNum++}
              } else {
                if (currentTag[key][2] && currentTag[key][2] !== '') {isPassNum++}
              }
            } else {
              isPassNum++
            }
            // console.log(key, "：", currentTag[key])
            break
          case 'ruleValues': // 规则参数
            if (this.typeStr === 1) {
              let tempRuleValuesNum = 0
              const expressionArr = currentTag['expressionArr']
              if (expressionArr) { expressionArr.forEach(item => { if(typeof item === 'number') { tempRuleValuesNum++ } }) }
              let tempNum = 0
              const tempRuleValues = currentTag['ruleValues']
              if (currentTag['tagRuleCodes'][2] === 'address') {tempRuleValuesNum = 3} // 标签
              if (currentTag['tagRuleCodes'][1] === 'c_address') {tempRuleValuesNum = 3} // 人群
              if (tempRuleValues) {tempRuleValues.forEach(item => { if (item[0] && item[0] !== '') {tempNum++} })}
              // 地区值可为 省、市
              if (currentTag['tagRuleCodes'][2] === 'address' || currentTag['tagRuleCodes'][1] === 'c_address') {
                if (tempNum > 0) {isPassNum++}
              } else if(JSON.stringify(currentTag.expression) === '{}') {
                isPassNum++
              } else {
                if (tempRuleValuesNum === tempNum) {isPassNum++}
              }
            } else {
              isPassNum++
            }
            break
          default: // 其它
            // console.log(key, "：", currentTag[key])
            // console.log('其它')
        }
      }
      // if (isPassNum !== 4) { return this.$message.warning('当前规则分层未填写完善！') }
      // if (!isPass) { return this.$message.warning('当前规则分层未填写完善！') }
      isPass = isPassNum === 4
      this.isPass = isPass
      return isPass
    },
    showInput () {
      const isPass = this.checkValues (this.currentTag)
      console.log(isPass)
      if (!isPass && this.dynamicTags.length !== 0) {
        this.$message.warning('新建分层前，请完善当前规则分层！')
        return
      }
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () {
      const inputValue = this.inputValue
      const dynamicTags = this.dynamicTags
      if (inputValue) {
        let isRepeat = false
        dynamicTags.forEach(item => { if (item.name === inputValue) { isRepeat = true } })
        if (isRepeat) { return this.$message.warning('重名！') }
        const tempObj = new CreateRule(inputValue, this.dynamicTags.length)
        tempObj.columnList[0] = this.tagRuleTypeList
        this.currentTag = tempObj
        this.dynamicTags.push(tempObj)
      }
      console.log(this.currentTag)
      /*
      this.dynamicTags.forEach((item,index) => {
        item.index = index
        item.sort = index
      })
      */
      this.inputVisible = false
      this.inputValue = ''
    },
    output (row) { this.$emit('tableShowDetail', row) },
    // 标签类型列表（三级树状）
    getTagRuleTypeList (type) {
      let methodFun, sessionName
      const rQuery = this.rQuery
      if (rQuery.type === 'group') {
        const classifyGroupRuleTypeList = JSON.parse(sessionStorage.getItem('classifyGroupRuleTypeList'))
        if (classifyGroupRuleTypeList) {
          this.tagRuleTypeList = classifyGroupRuleTypeList
          this.currentTag.columnList[0] = classifyGroupRuleTypeList
          return
        }
      } else {
        const tagRuleTypeList = JSON.parse(sessionStorage.getItem('tagRuleTypeList'))
        if (tagRuleTypeList) {
          this.tagRuleTypeList = tagRuleTypeList
          this.currentTag.columnList[0] = tagRuleTypeList
          return
        }
      }
      if (rQuery.type === 'group') {
        methodFun = this.$api.classifyGroupRuleTypeList
        sessionName = 'classifyGroupRuleTypeList'
      } else {
        methodFun = this.$api.tagRuleTypeList
        sessionName = 'tagRuleTypeList'
      }
      const params = {}
      methodFun(params).then((res) => {
        if (res.code === 0) {
          this.tagRuleTypeList = res.data
          this.currentTag.columnList[0] = res.data
          sessionStorage.setItem(sessionName, JSON.stringify(res.data))
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取、省、市、区
    getAddressList (type) {
      const addressList = JSON.parse(sessionStorage.getItem('addressList'))
      if (addressList) {
        this.addressList = addressList
        this.currentTag.addressList[0] = addressList
        return
      }
      const params = { dataType: 'address', parentId: 0 }
      this.$api.tagRuleParam(params).then((res) => {
        if (res.code === 0) {
          this.addressList = res.data
          this.currentTag.addressList[0] = res.data
          sessionStorage.setItem('addressList', JSON.stringify(res.data))
          // console.log(this.firstColumnList)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 一级改动
    firstColumnChangeAction (code, method) {
      // this.currentTag.columnList = [[], [], []] // 标签类型代码 - 列表
      // 给一级model赋值
      this.currentTag.tagRuleCodes[0] = code // 标签类型代码
      this.currentTag.columnList[0] = this.tagRuleTypeList
      // 初始化二级的列表
      const findObj = this.tagRuleTypeList.find(item => item.code === code)
      // const findObj = this.currentTag.columnList[0].find(item => item.code === code)
      // console.log(this.currentTag)
      // if (findObj) { this.currentTag.columnList[1] = findObj.childList }
      this.currentTag.columnList[1] = findObj.childList
      // console.log(this.currentTag.ruleValues[0][0] === '')
      if (method) {
        // 清空下级对象
        this.clearValue(10)
      } else {
        this.secondColumnChangeAction(this.currentTag.tagRuleCodes[1])
      }
    },
    // 二级改动
    secondColumnChangeAction (code, method) {
      const rQuery = this.rQuery
      if (rQuery.type === "group") {
        // 人群
        this.lastColumnChangeAction(code, method)
        return
      }
      // 给二级model赋值
      this.currentTag.tagRuleCodes[1] = code // 标签类型代码
      // 初始化三级的列表
      const findObj = this.currentTag.columnList[1].find(item => item.code === code)
      if (findObj) { this.currentTag.columnList[2] = findObj.childList }
      if (method) {
        // 清空下级对象
        this.clearValue(20)
      } else {
        this.thirdColumnChangeAction(this.currentTag.tagRuleCodes[2])
      }
    },
    // 人群
    lastColumnChangeAction (code, method) {
      // 给三级model赋值
      this.currentTag.tagRuleCodes[1] = code // 标签类型代码
      const findObj = this.currentTag.columnList[1].find(item => item.code === code)
      if (findObj && findObj.expression) { this.setExpressionArr (findObj) } else {
        this.currentTag.expression = {}
        this.currentTag.expressionArr = []
      }
      let str, dataType
      // const re = /（）/gi
      if (findObj && findObj.paramTypeList) {
        this.currentTag.paramTypeList = findObj.paramTypeList
        dataType = findObj.paramTypeList[0].dataType
      }
      if (dataType) {
        this.getTagRuleParam(dataType, 100, findObj.expression) // 标签类型下拉参数类型数据查询
      } else {
        if (method) {
          this.currentTag.ruleValues = [[''], [''], [''], [''], ['']] // 规则参数, 二维数组
        }
        // this.currentTag.paramTypeList = [{ dataType: '' }]
        this.currentTag.selectList.list = []
        // template = str.replace(re, `<el-input placeholder="请输入内容"></el-input>`)
      }
    },
    // 三级改动
    thirdColumnChangeAction (code, method) {
      // 给三级model赋值
      this.currentTag.tagRuleCodes[2] = code // 标签类型代码
      const findObj = this.currentTag.columnList[2].find(item => item.code === code)
      // console.log(findObj.expression)
      if (findObj && findObj.expression) { this.setExpressionArr (findObj) } else {
        this.currentTag.expression = {}
        this.currentTag.expressionArr = []
      }
      let str, dataType
      // const re = /（）/gi
      if (findObj && findObj.paramTypeList) {
        this.currentTag.paramTypeList = findObj.paramTypeList
        dataType = findObj.paramTypeList[0].dataType
      }
      if (dataType) {
        this.getTagRuleParam(dataType, 100, findObj.expression) // 标签类型下拉参数类型数据查询
      } else {
        if (method) {
          this.currentTag.ruleValues = [[''], [''], [''], [''], ['']] // 规则参数, 二维数组
        }
      }
    },
    // 标签类型下拉参数类型数据查询
    getTagRuleParam (dataType, index, method) {
      // if (index === 2) { return console.log('最后一个不请求') }
      let lIndex, value, addValue, methodFun
      this.currentTag.addressList[0].list = this.addressList
      if (dataType === 'address') {
        /*
        if (this.currentTag.addressList[index]) {
          const findValue = this.currentTag.addressList[index].value
          if (findValue) {
            const findObj = this.currentTag.addressList[index].list.find(item => item.value === findValue)
            console.log(findObj)
          }
        }
        */
        switch (index) {
          case 100:
            lIndex = 0
            value = 0
            // this.currentTag.addressList[0].value = ''
            addValue = this.currentTag.ruleValues[0][0]
            if (addValue) {
              const findObj = this.currentTag.addressList[0].list.find(item => item.value === addValue)
              this.currentTag.addressList[1].list = findObj.childList
              if (this.currentTag.ruleValues[1] && this.currentTag.ruleValues[1][0]) {
                const findObjj = this.currentTag.addressList[1].list.find(item => item.value === this.currentTag.ruleValues[1][0])
                this.currentTag.addressList[2].list = findObjj.childList

                if (this.currentTag.ruleValues[2] && this.currentTag.ruleValues[2][0]) {
                  const findObjj = this.currentTag.addressList[1].list.find(item => item.value === this.currentTag.ruleValues[1][0])
                  this.currentTag.addressList[2].list = findObjj.childList
                } else {
                  this.currentTag.ruleValues[2] = []
                  this.currentTag.ruleValues[2][0] = ''
                }
              } else {
                this.currentTag.ruleValues[1] = []
                this.currentTag.ruleValues[1][0] = ''
                this.currentTag.addressList[2].list = []
              }
            } else {
              this.currentTag.addressList[1].list = []
              this.currentTag.addressList[2].list = []
            }
            break
          case 0:
            lIndex = 1
            value = this.currentTag.ruleValues[0][0]
            addValue = this.currentTag.ruleValues[0][0]
            if (addValue) {
              const findObj = this.currentTag.addressList[0].list.find(item => item.value === addValue)
              this.currentTag.addressList[1].list = findObj.childList
              if (method) {
                this.currentTag.ruleValues[1][0] = ''
                this.currentTag.addressList[2].list = []
                this.currentTag.ruleValues[2][0] = ''
              }
            } else {
              this.currentTag.ruleValues[1][0] = ''
              this.currentTag.addressList[1].list = []
              this.currentTag.addressList[2].list = []
            }
            break
          case 1:
            /*
            lIndex = 2
            value = this.currentTag.ruleValues[1][0]
            addValue = this.currentTag.ruleValues[1][0]
            if (addValue) {
              console.log('addValue', addValue)
              const findObj = this.currentTag.addressList[1].list.find(item => item.value === addValue)
              this.currentTag.addressList[2].list = findObj.childList
              if (method) {
                this.currentTag.ruleValues[2] = []
                this.currentTag.ruleValues[2][0] = ''
              }
            } else {
              this.currentTag.addressList[2].list = []
            }
             */

            lIndex = 2
            value = this.currentTag.ruleValues[1][0]
            addValue = this.currentTag.ruleValues[1][0]
            if (addValue) {
              const findObj = this.currentTag.addressList[1].list.find(item => item.value === addValue)
              this.currentTag.addressList[2].list = findObj.childList
              if (method) {
                this.currentTag.ruleValues[2] = []
                this.currentTag.ruleValues[2][0] = ''
              }
            } else {
              // console.log(this.currentTag)
            }
            break
          default: // 2 为默认最后一个
              // console.log(this.currentTag.ruleValues)
            // debugger
            lIndex = 2
            value = this.currentTag.ruleValues[2][0]
            addValue = this.currentTag.ruleValues[2][0]
            if (addValue) {
              // console.log(typeof addValue, addValue)
              // const findObj = this.currentTag.addressList[1].list.find(item => item.value === addValue)
              // console.log(findObj)
              // this.currentTag.addressList[2].list = findObj.childList
              // this.currentTag.ruleValues[2] = []
              // this.currentTag.ruleValues[2][0] = addValue
            } else {
              // this.currentTag.ruleValues[2] = []
              // this.currentTag.ruleValues[2][0] = ''
              // this.currentTag.addressList[2].list = []
            }
            this.$forceUpdate()
        }
      }
      if (dataType === 'address') {
        // return console.log('省市区不需要请求！')
        return
      }
      const params = { dataType, parentId: value || 0 }
      if (this.rQuery.type === 'group') {
        methodFun = this.$api.classifyGroupRuleParam
      } else {
        methodFun = this.$api.tagRuleParam
      }
      methodFun(params).then((res) => {
        if (res.code === 0) {
          if (dataType === 'address') {
            // this.currentTag.addressList[lIndex].list = [].concat(res.data)
            // console.log(lIndex, this.currentTag.addressList[lIndex].list)
          } else {
            // console.log(this.currentTag)
            this.currentTag.selectList.list = res.data
          }
          // const re = /（）/gi
          // const str = this.currentTag.expression
          // const newstr = str.replace(re, '<el-input v-model="input" placeholder="请输入内容"></el-input>')
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    setExpressionArr (obj){
      const str = obj.expression
      // this.currentTag.expression = str.replace(re, '<input type="text"/>')
      this.currentTag.expression = str
      // this.currentTag.expressionArr = str.split('（）')
      this.currentTag.expressionArr = []
      let tempStr = ''
      let tempIndex = 0
      const tempNumArr = []
      // debugger
      for (let i = 0; i < str.length; i++) {
        // console.log(str[i])
        if (str[i] === '（') {
          tempNumArr.push(tempStr)
          tempNumArr.push(tempIndex)
          tempIndex++
          tempStr = ''
          i++
        } else {
          tempStr += str[i]
        }
      }
      if (tempStr !== '') { tempNumArr.push(tempStr) }
      this.currentTag.expressionArr = tempNumArr
      // console.log(this.currentTag.expressionArr)
    },
    clearValue (step) {
      switch (step) {
        case 10: // 第一
          this.currentTag.tagRuleCodes[1] = ''
          this.currentTag.tagRuleCodes[2] = ''
          this.currentTag.ruleValues= [[''], [''], [''], [''], ['']] // 规则参数, 二维数组
          this.currentTag.columnList[2] = []
          this.currentTag.expression = {}
          this.currentTag.expressionArr = []
          this.currentTag.paramTypeList = [{ dataType: '' }]
          this.currentTag.selectList = { value: '', list: [] }
          this.currentTag.addressList = [
            { value: '', list: [] },
            { value: '', list: [] },
            { value: '', list: [] }
          ]
          break
        case 20: // 第二
          this.currentTag.tagRuleCodes[2] = ''
          this.currentTag.ruleValues= [[''], [''], [''], [''], ['']] // 规则参数, 二维数组
          this.currentTag.expression = {}
          this.currentTag.expressionArr = []
          this.currentTag.paramTypeList = [{ dataType: '' }]
          this.currentTag.selectList = { value: '', list: [] }
          this.currentTag.addressList = [
            { value: '', list: [] },
            { value: '', list: [] },
            { value: '', list: [] }
          ]
          break
        case 30: // 第三
          // this.currentTag.ruleValues= [[''], [''], [''], [''], ['']] // 规则参数, 二维数组
          /*
          this.currentTag.addressList = [
            { value: '', list: [] },
            { value: '', list: [] },
            { value: '', list: [] }
          ]
            */
          break
        default: // 2 为默认最后一个
          console.log('没传参数！')
      }
    },
    // 表单规则验证
    submitForm (formName, type) {
      const rQuery = this.rQuery
      this.getRuleValues()
      const currentTag = Object.assign({}, this.currentTag)
      const dynamicTags = [].concat(this.dynamicTags)

      Object.assign(dynamicTags[currentTag.index], currentTag)
      dynamicTags.forEach(item => {
        // item.tagRuleCodes.filter(Boolean)
        if (rQuery.type === 'group') { item.tagRuleCodes.splice(2, 1) }
        item.groupDesc = item.desc
        item.ruleCodes = item.tagRuleCodes
        /*
        if (item.ruleValues) {
          const rvLen = item.ruleValues.length
          for (let i = 0; i < rvLen; i++) {
            if (item.ruleValues[i][0] === '') {
              item.ruleValues.splice(i, 5)
              break
            }
          }
        }
        */
      })
      const data = { dynamicTags, updateWay: this.updateWay }
      // console.log(data)
      const isRepeat = this.checkRepeat()
      if(isRepeat) {this.isPass = false}
      if(this.dynamicTags.length === 0) {this.isPass = false}
      this.$emit('ruleForm', data, this.isPass)
      /*
      this.$refs['basicForm'].validate((valid) => {
        if (valid) {
          // 不为空把表单值传入父组件
          this.$emit('basicForm', this.basicForm, true)
        } else {
          console.log('error submit!!')
          this.$emit('basicForm', this.basicForm, false)
          return false
        }
      })
      */
    }
  }
}
</script>
<style scoped lang="scss">
.setup-rule {
  .tag-list{
    margin: 12px 0;
    .el-button{width: 224px;text-align: left;margin: 5px;}
    .el-tag{
      position: relative;
      min-width: 224px;
      margin: 5px;
    }
    :deep(.el-tag .el-icon-close){
      position: absolute;
      top: -8px;
      right: -8px;
      border: 1px solid #409eff;
      border-radius: 50%;
      background-color: #ffffff;
      color: #409eff;
    }
    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .input-new-tag {
      width: 224px;
      margin: 5px;
      vertical-align: bottom;
    }
  }
  .currentTagForm{
    .el-form-item{
      &:nth-child(1), &:nth-child(2){
        width: 465px;
      }
    }
  }

  .update-method{
    .el-form-item__label{
      :deep(&:before){
        content: '*';
        color: #F56C6C;
      }
    }
    .el-radio-group{
      :deep(.el-radio-button .el-radio-button__inner){
        width: 128px;
        height: 36px;
        font-size: 16px;
        border-radius: 5px;
        background-color: rgba(236, 236, 236, 1);
        color: rgba(153, 153, 153, 1);
        border: none;
        box-shadow: none;
      }
      .el-radio-button + .el-radio-button{
        margin-left: 20px;
      }
      :deep(.is-active .el-radio-button__inner){
        background-color: rgba(227, 237, 255, 1);
        color: rgba(51, 51, 51, 1);
        font-weight: bold;
      }
    }
  }
}
.size12{
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #999999;
  margin-left: 68px;
}

.rule-linkage .el-form-item__content{
  .el-select{
    //width: 160px;
    margin-right: 10px;
  }
  .fourth-column-list{
    display: inline-block;
    padding: 1px 3px;
    //background-color: #FFBA00;
    :deep(input) {
      margin: 0 5px;
      height: 32px;
      line-height: 32px;
      width: 100px;
    }
  }
}
</style>
